package handler;

import Message.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获JWT过期异常
     * @param ex
     * @return
     */
    @ExceptionHandler(ExpiredJwtException.class)
    public Result handleExpiredJwtException(ExpiredJwtException ex){
        log.error("JWT token已过期：{}", ex.getMessage());
        return Result.tokenExpired();
    }

    /**
     * 捕获JWT解析异常
     * @param ex
     * @return
     */
    @ExceptionHandler(JwtException.class)
    public Result handleJwtException(JwtException ex){
        log.error("JWT token解析失败：{}", ex.getMessage());
        return Result.error(401, "token无效，请重新登录");
    }

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error("未知错误");
    }
}

